import { ipcMain } from 'electron'
import { getDmdbPool } from '../db/pool'

export const usersIpc = async (): Promise<void> => {
  const connection = await getDmdbPool()

  ipcMain.handle('userAdd', async (_, data) => {
    const { name, email } = data
    if (!name || !email) {
      return { message: '缺少必需的参数：name 或 email', code: 500 }
    }
    const sql = `INSERT INTO "USERS" ("NAME", "EMAIL") VALUES (?, ?)`
    await connection.execute(sql, [name, email])
    return { message: '用户新增成功', code: 200 }
  })

  ipcMain.handle('userDel', async (_, data) => {
    const { id } = data
    if (!id) {
      return { message: '缺少必需的参数：id', code: 500 }
    }
    const sql = `DELETE FROM "USERS" WHERE "ID" = ?`
    await connection.execute(sql, [id])
    return { message: '用户删除成功', code: 200 }
  })

  ipcMain.handle('userList', async () => {
    const sql = `SELECT * FROM "USERS"`
    const queryResult = await connection.execute(sql)
    // 解析查询结果
    const metaData = queryResult.metaData.map((column) => column.name) // 获取列名
    const rows = queryResult.rows // 获取真正的行数据

    // 将每行数据映射为对象格式
    const users = rows.map((row) => {
      const user: Record<string, any> = {}
      metaData.forEach((key, index) => {
        user[key] = row[index] // 根据列名赋值
      })
      return user
    })
    return users
  })
}
